import cookie from "js-cookie";
import CryptoJS from 'crypto-js';

/**
 * 请求时间
 * @return {String} yyyyMMddHHmmss格式参数
 */
exports.reqTime=function(){
    function pad2(n) { return n < 10 ? '0' + n : n; }
    let date = new Date();
    return date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2(date.getDate()) + pad2(date.getHours()) + pad2(date.getMinutes()) + pad2(date.getSeconds());
};

/**
 * 请求流水号
 * @return {String} [密文参数req_seq参数]
 */
exports.reqNo=function(){
    let ramdomNumber=Math.random().toString().slice(2,8);
    return exports.reqTime()+ramdomNumber;
};

/**
 * 时间戳格式化
 * @param  {time}   time 时间戳
 * @return {String}      格式化时间
 */
exports.formatTime = function (time){
    let date = new Date(time);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    let D = (date.getDate() < 10 ? '0'+ (date.getDate()) : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0'+ (date.getHours()) : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0'+ (date.getMinutes()) : date.getMinutes()) + ':';
    let s = (date.getSeconds() < 10 ? '0'+ (date.getSeconds()) : date.getSeconds());
    return Y+M+D+h+m+s;
};
exports.formatDate = function (time){
    let date = new Date(time);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    let D = (date.getDate() < 10 ? '0'+ (date.getDate()) : date.getDate()) + ' ';
    return Y+M+D;
};

/**
* [解码tokenId 的 base64字符串]
* @param  {[type]} base64 [base64编码字符串]
* @return {[type]}        [加码字符串]
*/
exports.getTokenId = function () {
    let decodeStr = function (base64Str){
        let parsedWordArray = CryptoJS.enc.Base64.parse(base64Str);
        // console.log('parsedWordArray', parsedWordArray.toString());
        let parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8);
        // console.log('base64Decrypt = ',parsedStr);
        return parsedStr;
    };
    let t1 = decodeStr(cookie.get('a1To')?cookie.get('a1To'):"");
    let t2 = decodeStr(cookie.get('ncs')?cookie.get('ncs'):"");
    let t3 = decodeStr(cookie.get('idTo3')?cookie.get('idTo3'):"");
    let tokenId = cookie.get('tokenId');
    return t1+t2+t3;
};

/**
 * 把desKey混淆放进cookie
 * @type {[type]}
 */

const forDesKey = '1C5221DAC9B6E3BCF789F607';
// 如果浏览器报 `error malformed utf-8 data` ，可以把forDesKey写成固定的任意字符串
// const forDesKey = Number(String(Math.random()).slice(2,10));
let randomStr = Number(String(Math.random()).slice(2)).toString(36).toUpperCase().slice(0, 8);

const sKey = "3C6261D7B9B6E3BCF647F647";
let desKey = sKey + randomStr;
let forKeyHex = CryptoJS.enc.Utf8.parse(forDesKey);

exports.setDesKeyInCookie = function () {
    // console.log('randomStr:', randomStr);
    // console.log('forDesKey:', forDesKey);
    if(cookie.get('dek') && cookie.get('c2cok')){
        // console.log('des key cookie 存在了');
        return ;
    }

    let keyHex = CryptoJS.enc.Utf8.parse(desKey);
    // let forKeyHex = CryptoJS.enc.Utf8.parse(forDesKey);

    let desEncrypted = CryptoJS.TripleDES.encrypt(desKey, forKeyHex, {
        iv: CryptoJS.enc.Utf8.parse(forKeyHex),
        // iv: forKeyHex,
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    let desEncryptedStr = desEncrypted.toString();
    let len = desEncryptedStr.length;
    let rand = Math.floor(Math.random()*(len/2));
    let c1 = desEncryptedStr.slice(0, rand);
    let c2 = desEncryptedStr.slice(rand);
    let c3 = desEncryptedStr.slice(-rand);
    cookie.set('dek', c1, { expires: 7 });
    cookie.set('c2cok', c2, { expires: 7 });

    // 这个是没用，混乱用户的
    cookie.set('a2c', c3, { expires: 7 });
    // console.log("desEncryptedStr:", desEncryptedStr);
    // console.log("c1:", c1);
    // console.log("c2:", c2);
};

/**
 * 获取cookie里的des key
 * 注意：
 * 如果被别人改了cookie，不能正常解析，返回的会是空
 * @return {[String]} [DES对称加密的Key]
 */

exports.getDesKeyFromCookie = function getDesKeyFromCookie() {
    if(!cookie.get('dek') || !cookie.get('c2cok')){
        console.log("des key 不完整");
        exports.setDesKeyInCookie();
    }
    // let forDesKey = "nicetogo";
    // let forKeyHex = CryptoJS.enc.Utf8.parse(forDesKey);

    let c1 = cookie.get('dek');
    let c2 = cookie.get('c2cok');
    let desStr = c1 + c2;
    let desDecrypted = CryptoJS.TripleDES.decrypt(desStr, forKeyHex, {
        iv: CryptoJS.enc.Utf8.parse(forKeyHex),
        // iv: forKeyHex,
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    // let desDecryptedStr = CryptoJS.enc.Utf8.stringify(desDecrypted).slice(0, -8);
    let desDecryptedStr = CryptoJS.enc.Utf8.stringify(desDecrypted);
    if(!desDecryptedStr){
        // debugger;
        cookie.remove('dek');
        cookie.remove('c2cok');
        cookie.remove('a2c');
        exports.setDesKeyInCookie();
        desDecryptedStr = getDesKeyFromCookie();
        return desDecryptedStr;
    }
    // console.log('解密后desDecryptedStr:', desDecryptedStr);
    return desDecryptedStr;
};

/**
 * 把RSAKey混淆放进cookie
 * @type {[type]}
 */

const forRSAKey = 'nicetomeetyou';
const rsaKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHSmGkXWyU6EHbBQ1+R4M/6Yyo0Ojir/iUutHCrhzHGHkS2OIN4Gys36AdItdB8z051qujLCni6UpjRzCjPkRWg7VDA2/MyNo6brHfIQs+JTHCgdPmvXZkg0oleADOMsQzIVnk6kZfXUVCKYxAK6/6i/0Kt7LjOcMEo3EWuPV2kQIDAQAB";
const rsaKeyLen = rsaKey.length;
exports.setRSAKeyInCookie = function () {
    // console.log(forRSAKey);
    if(cookie.get('r_data') && cookie.get('sped') && cookie.get('add_Val')) {
        // console.log('des key cookie 存在了');
        return ;
    }

    let rand1 = Math.floor(Math.random()*(rsaKeyLen/3));
    let rand2 = Math.floor(Math.random()*(rsaKeyLen/2));
    rand1 = rand1>rand2?rand2:rand1;
    let c1 = rsaKey.slice(0, rand1);
    let c2 = rsaKey.slice(rand1, rand2);
    let c3 = rsaKey.slice(rand2);
    cookie.set('r_data', c1, { expires: 7 });
    cookie.set('sped', c2, { expires: 7 });
    cookie.set('add_Val', c3, { expires: 7 });

    // 这个是没用，混乱用户的
    let c4 = rsaKey.slice(parseInt(rsaKey.slice(0,8)), 36);
    cookie.set('a3_cook_io', c4, { expires: 7 });
    // console.log("RSAEncryptedStr:", rsaKey);
    // console.log("c1:", c1);
    // console.log("c2:", c2);
    // console.log("c3:", c3);
};

/**
 * 获取cookie里的RSA key
 * @return {[String]} [RSA对称加密的公钥]
 */

exports.getRSAKeyFromCookie = function () {
    if(!cookie.get('r_data') || !cookie.get('sped') || !cookie.get('add_Val')){
        console.log("rsa key 不完整");
        exports.setRSAKeyInCookie();
    }

    let c1 = cookie.get('r_data');
    let c2 = cookie.get('sped');
    let c3 = cookie.get('add_Val');
    let rsaPublicKey = c1 + c2 + c3;
    return rsaPublicKey;
};

/**
 * 邓易写的，手动解释cookie
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
exports.getCookie = function (name){
    name = name + "=";
    let start = document.cookie.indexOf(name);
    let value = null;
    if(start>-1){
        let end = document.cookie.indexOf(";",start);
        if(end === -1){
            end = document.cookie.length;
        }
        value = document.cookie.substring(start+name.length,end);
    }
    return value;
};
